<template>
  <div class="image-manager">
    <div class="header">
      <h2>商品图片管理</h2>
      <div class="controls">
        <select v-model="selectedShoeId" @change="loadImages">
          <option value="">选择商品</option>
          <option v-for="shoe in shoes" :key="shoe.shoeId" :value="shoe.shoeId">
            {{ shoe.name }} (ID: {{ shoe.shoeId }})
          </option>
        </select>
        <button @click="loadShoes" class="btn-secondary">刷新商品列表</button>
      </div>
    </div>

    <div v-if="selectedShoeId" class="content">
      <!-- 图片上传区域 -->
      <div class="upload-section">
        <h3>上传图片</h3>
        <div class="upload-area">
          <input 
            type="file" 
            ref="fileInput" 
            multiple 
            accept="image/*" 
            @change="handleFileSelect"
            style="display: none"
          >
          <button @click="$refs.fileInput.click()" class="btn-primary">
            选择图片文件
          </button>
          <span v-if="selectedFiles.length > 0" class="file-count">
            已选择 {{ selectedFiles.length }} 个文件
          </span>
        </div>
        
        <div v-if="selectedFiles.length > 0" class="file-preview">
          <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
            <img :src="getFilePreview(file)" alt="预览" class="preview-img">
            <span class="file-name">{{ file.name }}</span>
            <button @click="removeFile(index)" class="btn-remove">×</button>
          </div>
        </div>

        <div class="upload-actions">
          <button 
            @click="uploadImages" 
            :disabled="selectedFiles.length === 0 || uploading"
            class="btn-primary"
          >
            {{ uploading ? '上传中...' : '上传图片' }}
          </button>
        </div>
      </div>

      <!-- 图片列表 -->
      <div class="images-section">
        <h3>商品图片列表</h3>
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="images.length === 0" class="empty">暂无图片</div>
        <div v-else class="images-grid">
          <div v-for="image in images" :key="image.imageId" class="image-item">
            <div class="image-wrapper">
              <img :src="getImageUrl(image.imageUrl)" :alt="image.imageName" class="product-image">
              <div class="image-overlay">
                <button 
                  @click="setMainImage(image.imageId)" 
                  :class="['btn-main', { active: image.isMain }]"
                >
                  {{ image.isMain ? '主图' : '设为主图' }}
                </button>
                <button @click="deleteImage(image.imageId)" class="btn-delete">删除</button>
              </div>
            </div>
            <div class="image-info">
              <p class="image-name">{{ image.imageName }}</p>
              <p class="image-type">类型: {{ image.imageType }}</p>
              <p class="image-order">排序: {{ image.sortOrder }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="no-selection">
      <p>请先选择一个商品来管理图片</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ProductImageManager',
  data() {
    return {
      shoes: [],
      selectedShoeId: '',
      images: [],
      selectedFiles: [],
      loading: false,
      uploading: false
    }
  },
  mounted() {
    this.loadShoes()
  },
  methods: {
    async loadShoes() {
      try {
        const response = await axios.get('http://localhost:8080/api/v1/shoes/list')
        if (response.data.success) {
          this.shoes = response.data.data
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        alert('加载商品列表失败')
      }
    },

    async loadImages() {
      if (!this.selectedShoeId) {
        this.images = []
        return
      }

      this.loading = true
      try {
        const response = await axios.get(`http://localhost:8080/api/v1/shoes/${this.selectedShoeId}/images`)
        if (response.data.success) {
          this.images = response.data.data || []
        }
      } catch (error) {
        console.error('加载图片列表失败:', error)
        alert('加载图片列表失败')
      } finally {
        this.loading = false
      }
    },

    handleFileSelect(event) {
      const files = Array.from(event.target.files)
      this.selectedFiles = files
    },

    removeFile(index) {
      this.selectedFiles.splice(index, 1)
    },

    getFilePreview(file) {
      return URL.createObjectURL(file)
    },

    getImageUrl(url) {
      if (url.startsWith('http')) {
        return url
      }
      return `http://localhost:8080${url}`
    },

    async uploadImages() {
      if (this.selectedFiles.length === 0) return

      this.uploading = true
      try {
        const formData = new FormData()
        this.selectedFiles.forEach(file => {
          formData.append('files', file)
        })

        const response = await axios.post(
          `http://localhost:8080/api/v1/shoes/upload-images/${this.selectedShoeId}`,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )

        if (response.data.success) {
          alert('图片上传成功')
          this.selectedFiles = []
          this.$refs.fileInput.value = ''
          this.loadImages()
        } else {
          alert('图片上传失败: ' + response.data.message)
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        alert('图片上传失败')
      } finally {
        this.uploading = false
      }
    },

    async setMainImage(imageId) {
      try {
        const response = await axios.post(`http://localhost:8080/api/v1/shoes/set-main-image/${imageId}`)
        if (response.data.success) {
          alert('设置主图成功')
          this.loadImages()
        } else {
          alert('设置主图失败: ' + response.data.message)
        }
      } catch (error) {
        console.error('设置主图失败:', error)
        alert('设置主图失败')
      }
    },

    async deleteImage(imageId) {
      if (!confirm('确定要删除这张图片吗？')) return

      try {
        const response = await axios.post(`http://localhost:8080/api/v1/shoes/delete-image/${imageId}`)
        if (response.data.success) {
          alert('删除图片成功')
          this.loadImages()
        } else {
          alert('删除图片失败: ' + response.data.message)
        }
      } catch (error) {
        console.error('删除图片失败:', error)
        alert('删除图片失败')
      }
    }
  }
}
</script>

<style scoped>
.image-manager {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #eee;
}

.controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.controls select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.upload-section {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.upload-area {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.file-count {
  color: #666;
  font-size: 14px;
}

.file-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.preview-img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.file-name {
  font-size: 12px;
  color: #666;
  max-width: 100px;
  
  text-overflow: ellipsis;
  white-space: nowrap;
}

.btn-remove {
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  cursor: pointer;
  font-size: 12px;
}

.images-section h3 {
  margin-bottom: 20px;
}

.loading, .empty {
  text-align: center;
  padding: 40px;
  color: #666;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.image-item {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  
  transition: transform 0.2s;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.image-wrapper {
  position: relative;
  height: 200px;
  
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.btn-main {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  background: #2ecc71;
  color: white;
}

.btn-main.active {
  background: #f39c12;
}

.btn-delete {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  background: #e74c3c;
  color: white;
}

.image-info {
  padding: 15px;
}

.image-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}

.image-name {
  font-weight: bold;
  color: #333 !important;
}

.btn-primary {
  background: #3498db;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.no-selection {
  text-align: center;
  padding: 60px;
  color: #666;
  font-size: 16px;
}
</style>